<template>
  <div class="map-container">
    <div class="mapCheckedBox">
      <el-checkbox v-model="areaChecked" class="white-text-checkbox"
        >显示情报区域范围</el-checkbox
      >
    </div>
    <div ref="chartRef" class="chart-container"></div>
    <div class="mapTabs">
      <div
        class="tab"
        @click="handleDetail('6')"
        :class="{ tabCur: currTabIndex == '6' }"
      >
        航路预测详情
      </div>
      <div
        @click="handleDetail('7')"
        class="tab"
        :class="{ tabCur: currTabIndex == '7' }"
      >
        航线预测详情
      </div>
    </div>
    <NoDatas
      v-if="currTabIndex == '6'"
      @update-curr-detail-index="handleTabChange"
    />
  </div>
</template>

<script setup>
import {
  ref,
  onMounted,
  onUnmounted,
  watch,
  nextTick,
  computed,
  defineProps,
} from "vue";
import * as echarts from "echarts/core";
import { ElMessage } from "element-plus";
import isValidValue from "@/utils/tools/isValidValue";
import {
  GraphicComponent,
  GeoComponent,
  TooltipComponent,
} from "echarts/components";
import { MapChart, LinesChart, ScatterChart } from "echarts/charts";
import { CanvasRenderer } from "echarts/renderers";
// import DetailArea from "./detailArea.vue";
import NoDatas from "./noDatas.vue";
import { firApi } from "@/api/tabOne";

// 注册所需模块
echarts.use([
  GeoComponent,
  MapChart,
  ScatterChart,
  LinesChart,
  CanvasRenderer,
  TooltipComponent,
  GraphicComponent,
]);

// 接收父组件传递的机场数据
const props = defineProps({
  airports: {
    type: Array,
    default: () => [],
  },
  areaStatic1: {
    type: Array,
    default: () => [],
  },
  airTestsAreaObj: {
    type: Array,
    default: () => [],
  },
});

const currTabIndex = ref("");
// const airTestsArea2Obj = ref([]); // 单个区域终端详情

// 组件状态
const areaChecked = ref(false);
const chartRef = ref(null);
const chart = ref(null);
const isReady = ref(false);
const lineWidth = computed(() => 1);
const gridLines = ref([]);
const gridSize = ref(2.5);
const visibleRange = ref({
  minLon: 0,
  maxLon: 0,
  minLat: 0,
  maxLat: 0,
});
const isFirstLoad = ref(true);
const pathData = ref([]); // 存储请求返回的路径数据
const pathSeriesName = "simulatePath"; // 路径系列的唯一名称（用于定位和删除）

const legendConfig = computed(() => {
  // 情况1：显示 areaStatic 的图例（2个元素：红色矩形 + “不可用”文本）
  if (isValidValue(props.areaStatic1)) {
    const legendItems = [
      { color: "#7cfa8d", text: "0", top: 20 },
      { color: "#4dad51", text: "1-5", top: 45 },
      { color: "#2f7132", text: "6-10", top: 70 },
      { color: "#d7fc62", text: "11-20", top: 95 },
      { color: "#fcfe54", text: "21-30", top: 120 },
      { color: "#f8cf59", text: "31-40", top: 145 },
      { color: "#f19135", text: "41-50", top: 170 },
      { color: "#ee692c", text: "51-60", top: 195 },
      { color: "#ec3323", text: ">60", top: 220 },
    ];
    let legendArr = [];
    legendItems.forEach((item) => {
      legendArr.push({
        type: "rect",
        right: 60,
        top: item.top,
        zlevel: 5,
        shape: { width: 12, height: 12 },
        style: { fill: item.color },
      });
      legendArr.push({
        type: "text",
        right: 20,
        top: item.top,
        zlevel: 5,
        style: { text: item.text, fontSize: 12, fill: "#ffffff" },
      });
    });
    return legendArr;
  }
  // 情况3：两者都不存在，返回空数组（彻底清除所有图例）
  else {
    return [];
  }
});

const handleTabChange = (newTabIndex) => {
  currTabIndex.value = newTabIndex;
};

// 地图常量配置
const MAP_CONFIG = {
  backgroundColor: "transparent",
};

// 异步加载地图数据
const loadMapData = async () => {
  try {
    const { default: chinaJson } = await import("@/assets/china.json");
    echarts.registerMap("china", chinaJson);
    return true;
  } catch (error) {
    console.error("地图数据加载失败:", error);
    return false;
  }
};

const getFir = async () => {
  const { code, msg, data } = await firApi();
  if (code === 200) {
    return data;
  } else {
    ElMessage({ message: msg, type: "warning" });
  }
};

const handleDetail = (index) => {
  console.log(index, "index");
  console.log(props.airTestsAreaObj, "props.airTestsAreaObj");
  if (index == 2 && isValidValue(props.airTestsAreaObj)) {
    currTabIndex.value = index;
    console.log(currTabIndex.value);
  } else {
    console.log("null6");
    currTabIndex.value = "6";
  }
};

// 绘制网格 - 只在首次加载时执行
const drawGrid = () => {
  if (!isReady.value || !isFirstLoad.value) return;

  gridLines.value = generateGridData();
  const option = chart.value.getOption();
  const nonGridSeries = option.series.filter(
    (series) => series.type === "map" || series.type === "scatter"
  );

  chart.value.setOption({
    series: [...nonGridSeries, ...gridLines.value],
  });
};

// 生成网格线数据
const generateGridData = () => {
  const lines = [];
  const { minLon, maxLon, minLat, maxLat } = visibleRange.value;
  const step = gridSize.value;

  const startLat = Math.ceil(minLat / step) * step;
  const endLat = Math.floor(maxLat / step) * step;

  for (let lat = startLat; lat <= endLat; lat += step) {
    const fixedLat = Number(lat.toFixed(1));
    lines.push({
      tip: "绘制网格线",
      type: "lines",
      zlevel: 3,
      name: `纬线_${fixedLat}`,
      coordinateSystem: "geo",
      polyline: true,
      lineStyle: {
        width: lineWidth.value,
        color: "rgba(0,59,122,1)",
        type: "solid",
      },
      emphasis: {
        disabled: false,
      },
      data: [
        [
          [minLon, fixedLat],
          [maxLon, fixedLat],
        ],
      ],
    });
  }

  const startLon = Math.ceil(minLon / step) * step;
  const endLon = Math.floor(maxLon / step) * step;

  for (let lon = startLon; lon <= endLon; lon += step) {
    const fixedLon = Number(lon.toFixed(1));
    lines.push({
      type: "lines",
      name: `经线_${fixedLon}`,
      zlevel: 3,
      coordinateSystem: "geo",
      polyline: true,
      lineStyle: {
        width: lineWidth.value,
        color: "rgba(0,59,122,1)",
        type: "solid",
      },
      emphasis: {
        disabled: false, // 开启，否则无法触发 tooltip
      },
      data: [
        [
          [fixedLon, minLat],
          [fixedLon, maxLat],
        ],
      ],
    });
  }

  return lines;
};

// 初始化图表 - 只在首次加载时执行
const initChart = () => {
  if (!isReady.value || !chart.value || !isFirstLoad.value) return;

  const option = {
    backgroundColor: MAP_CONFIG.backgroundColor,
    graphic: legendConfig.value,
    tooltip: {
      show: true,
      trigger: "item",
      formatter: (params) => {
        if (params.seriesType === "lines") {
          const name = params.seriesName;
          if (name.startsWith("纬线_")) {
            const lat = name.split("_")[1];
            return `纬线: ${lat}°N`;
          }
          // 匹配经线（格式：经线_102.5）
          else if (name.startsWith("经线_")) {
            const lon = name.split("_")[1];
            return `经线: ${lon}°E`;
          }
          return "网格线信息";
        }

        if (!params.value || !Array.isArray(params.value)) {
          return "经纬度信息";
        }
        const lon = Number(params.value[0]);
        const lat = Number(params.value[1]);
        if (isNaN(lon) || isNaN(lat)) {
          return "经纬度信息";
        }
        return `经度: ${lon.toFixed(4)}°<br>纬度: ${lat.toFixed(4)}°`;
      },
    },
    geo: {
      map: "china",
      // aspectScale: 0.75,
      // layoutCenter: [450, 337.5], //["50%", "52%"],
      // layoutSize: "90%",
      center: [104, 31], // 中国几何中心经纬度（可自定义）
      zoom: 1.2, // 缩放级别（1 为默认，越大地图越近）
      roam: false,
      emphasis: {
        disabled: true,
      },
      itemStyle: {
        normal: {
          borderColor: "#4896a4",
          borderWidth: 0.5,
          color: {
            type: "linear-gradient",
            x: 0,
            y: 1500,
            x2: 2500,
            y2: 0,
            colorStops: [
              { offset: 0, color: "#132c5f" },
              { offset: 1, color: "#132c5f" },
            ],
            global: true,
          },
          opacity: 0.5,
        },
        emphasis: {
          areaColor: "rgba(0, 157, 161, 0.5)",
          borderColor: "rgba(147, 235, 248, 1)",
        },
      },
      regions: [
        {
          name: "南海诸岛",
          itemStyle: {
            areaColor: "rgba(0, 10, 52, 1)",
            borderColor: "rgba(0, 10, 52, 1)",
          },
          emphasis: {
            areaColor: "rgba(0, 10, 52, 1)",
            borderColor: "rgba(0, 10, 52, 1)",
          },
        },
      ],
      z: 1,
    },
    series: [
      {
        type: "map",
        map: "china",
        tooltip: { show: false },
        label: {
          show: false,
        },

        center: [104, 30.8],
        zoom: 1.2,
        roam: false,
        emphasis: {
          disabled: true,
        },
        itemStyle: {
          normal: {
            borderColor: "rgba(147, 235, 248, 0.6)",
            borderWidth: 0.8,
            areaColor: {
              type: "linear-gradient",
              x: 0,
              y: 1200,
              x2: 1000,
              y2: 0,
              colorStops: [
                { offset: 0, color: "#132c5f" },
                { offset: 1, color: "#132c5f" },
              ],
              global: true,
            },
          },
          emphasis: {
            areaColor: "rgba(0, 157, 161, 0.5)",
            borderColor: "rgba(147, 235, 248, 0.6)",
          },
        },
        zlevel: 0,
      },
    ],
  };

  chart.value.setOption(option);

  nextTick(async () => {
    await new Promise((resolve) => setTimeout(resolve, 100));

    const container = chartRef.value;
    const { width: containerWidth, height: containerHeight } =
      container.getBoundingClientRect();

    const topLeft = chart.value.convertFromPixel("geo", [0, 0]);
    const topRight = chart.value.convertFromPixel("geo", [containerWidth, 0]);
    const bottomLeft = chart.value.convertFromPixel("geo", [
      0,
      containerHeight,
    ]);
    const bottomRight = chart.value.convertFromPixel("geo", [
      containerWidth,
      containerHeight,
    ]);

    const actualMinLon = Math.min(
      topLeft[0],
      topRight[0],
      bottomLeft[0],
      bottomRight[0]
    );
    const actualMaxLon = Math.max(
      topLeft[0],
      topRight[0],
      bottomLeft[0],
      bottomRight[0]
    );
    const actualMinLat = Math.min(
      topLeft[1],
      topRight[1],
      bottomLeft[1],
      bottomRight[1]
    );
    const actualMaxLat = Math.max(
      topLeft[1],
      topRight[1],
      bottomLeft[1],
      bottomRight[1]
    );

    visibleRange.value = {
      minLon: actualMinLon,
      maxLon: actualMaxLon,
      minLat: actualMinLat,
      maxLat: actualMaxLat,
    };

    drawGrid();
    updateAirports();
    isFirstLoad.value = false;
    bindAirportDoubleClick();
  });
};
// 根据区域的 pointId 筛选目标区域数据
// const filterByAirAreaName = (originalData, targetPointId) => {
//   const newData = JSON.parse(JSON.stringify(originalData));
//   const filteredAreaResults = newData.filter((item) => {
//     return item?.area?.pointId === targetPointId;
//   });
//   return filteredAreaResults;
// };
// 绑定双击事件
const bindAirportDoubleClick = () => {
  if (!chart.value) return;

  // // 监听图表双击事件
  // chart.value.on("dblclick", (params) => {
  //   // 静态区域统计矩形双击逻辑
  //   if (params.seriesName === "areaStaticStatRect") {
  //     airTestsArea2Obj.value = filterByAirAreaName(
  //       props.airTestsAreaObj,
  //       params.data.area.pointId
  //     );
  //     currTabIndex.value = "2Spa";
  //   }
  // });
};

// 更新机场数据
const updateAirports = () => {
  if (!isReady.value || !chart.value) return;
  // const greenPlane = new URL(
  //   "../../../assets/images/raim/airlvicon.png",
  //   import.meta.url
  // ).href;

  // const airportData = props.airports.map((airport) => ({
  //   name: airport.name,
  //   value: [airport.longitude, airport.latitude],
  //   ...airport,
  // }));

  const option = chart.value.getOption();
  // const oldAirportSeriesIndex = option.series.findIndex(
  //   (s) => s.name === "airports"
  // );
  // if (oldAirportSeriesIndex !== -1) {
  //   option.series[oldAirportSeriesIndex].data = airportData.map((item) => ({
  //     ...item,
  //     symbol: `image://${greenPlane}`,
  //     symbolSize: [18, 30],
  //     zlevel: 5,
  //   }));
  //   // option.series.splice(oldAirportSeriesIndex, 1);
  // } else {
  //   option.series.push({
  //     type: "scatter",
  //     name: "airports",
  //     coordinateSystem: "geo",
  //     zlevel: 4,
  //     // 飞机系列的tooltip配置
  //     tooltip: {
  //       show: true,
  //       trigger: "item",
  //       padding: 12,
  //       backgroundColor: "rgba(0, 15, 40, 0.9)",
  //       borderColor: "rgba(147, 235, 248, 0.8)",
  //       borderWidth: 1,
  //       textStyle: { color: "#fff", fontSize: 13, lineHeight: 1.5 },
  //       formatter: (params) => {
  //         if (params.data?.isBigPlane) {
  //           return `
  //           <div>
  //             <p><b>机场名称：</b>${params.data.name || "未知"}</p>
  //             <p><b>经度：</b>${params.data.longitude?.toFixed(4) || "未知"}</p>
  //             <p><b>纬度：</b>${params.data.latitude?.toFixed(4) || "未知"}</p>
  //           </div>
  //         `;
  //         }
  //         return "";
  //       },
  //     },
  //     data: airportData.map((item) => {
  //       return {
  //         ...item,
  //         symbol: `image://${greenPlane}`,
  //         symbolSize: [18, 30],
  //         zlevel: 5,
  //       };
  //     }),
  //   });
  // }

  if (isValidValue(props.areaStatic1)) {
    const oldAreaStaticIndex = option.series.findIndex(
      (s) => s.name === "areaStaticStatRect"
    );
    if (oldAreaStaticIndex !== -1) {
      option.series.splice(oldAreaStaticIndex, 1);
    }

    const rectWidth = 22;
    const rectHeight = 32;
    const pixelOffsetLon = 18;
    const pixelOffsetLat = 18;
    const { width: containerWidth } = chartRef.value.getBoundingClientRect();
    const geoModel = chart.value.getModel().getComponent("geo");
    const [visMinLon, visMaxLon] = geoModel.option.longitudeRange || [73, 135];
    const lonRange = visMaxLon - visMinLon;

    const pixelToLon = lonRange / containerWidth;
    const pixelToLat = pixelToLon;

    const offsetLon = pixelOffsetLon * pixelToLon;
    const offsetLat = pixelOffsetLat * pixelToLat;

    const colorLevelMap = {
      0: "#7cfa8d",
      1: "#4dad51",
      2: "#2f7132",
      3: "#d7fc62",
      4: "#fcfe54",
      5: "#f8cf59",
      6: "#f19135",
      7: "#ee692c",
      8: "#ec3323",
    };

    const rectSeriesStatData = props.areaStatic1.map((item) => {
      // 从 item.area 中提取经纬度（原代码是 item.longitude）
      const { longitude: lon, latitude: lat } = item.area;
      const gridSizeVal = gridSize.value;

      const baseAlignedLon = Math.round(lon / gridSizeVal) * gridSizeVal;
      const baseAlignedLat = Math.round(lat / gridSizeVal) * gridSizeVal;

      const alignedLon = baseAlignedLon + offsetLon;
      const alignedLat = baseAlignedLat + offsetLat;

      return {
        name: `静态区域${item.pointId}`,
        value: [alignedLon, alignedLat],
        ...item,
        alignedLon,
        alignedLat,
      };
    });

    option.series.push({
      type: "scatter",
      name: "areaStaticStatRect",
      coordinateSystem: "geo",
      zlevel: 4,
      symbol: "rect",
      symbolSize: [rectWidth, rectHeight],
      itemStyle: {
        color: (params) => {
          const level = params.data.colorLevel;
          return colorLevelMap[level] || "rgba(200, 200, 200, 0.4)";
        },
      },
      tooltip: {
        show: true,
        trigger: "item",
        formatter: (params) => {
          const point = params.data;
          return `
          <div>
            <p><b>区域ID：</b>${point.pointId}</p>
            <p><b>偏移后经纬度：</b>${point.alignedLon.toFixed(
              4
            )}, ${point.alignedLat.toFixed(4)}</p>
            <p><b>视觉偏移：</b>经度${pixelOffsetLon}px，纬度${pixelOffsetLat}px</p>
          </div>
        `;
        },
      },
      data: rectSeriesStatData,
    });
  } else {
    const oldAreaStaticIndex1 = option.series.findIndex(
      (s) => s.name === "areaStaticStatRect"
    );
    if (oldAreaStaticIndex1 !== -1) {
      option.series.splice(oldAreaStaticIndex1, 1);
    }
  }

  chart.value.setOption(option);
};

const forceUpdateGraphic = () => {
  if (!chart.value || !isReady.value) return;
  const option = chart.value.getOption();

  option.graphic = legendConfig.value;
  // 调用 setOption 时添加 silent: false，强制 ECharts 重绘图例，清除残留
  chart.value.setOption(option, {
    silent: false,
    replaceMerge: ["graphic"],
  });
};

watch(
  areaChecked,
  async (isChecked) => {
    if (!isReady.value || !chart.value) return;

    const option = chart.value.getOption();
    if (isChecked) {
      try {
        const simulateData = await getFir();
        pathData.value = simulateData;
        option.series = option.series.filter((s) => s.name !== pathSeriesName);

        const pathSeries = simulateData
          .filter(
            (item) =>
              item?.shapePoints &&
              Array.isArray(item.shapePoints) &&
              item.shapePoints.length > 0
          )
          .map((item) => {
            const validCoords = item.shapePoints.map((point) => [
              point.longitude,
              point.latitude,
            ]);
            if (validCoords.length < 2) {
              console.warn(
                `路径${item.identifier}有效坐标不足2个，跳过绘制`,
                validCoords
              );
              return null;
            }

            // 正常生成路径系列
            return {
              type: "lines",
              name: pathSeriesName,
              zlevel: 7,
              coordinateSystem: "geo",
              polyline: true,
              lineStyle: {
                width: 1,
                color: "#00AFFF",
                opacity: 1.0,
                dashOffset: 5,
                type: "dashed",
              },
              tooltip: {
                show: true,
                formatter: () => `路径：${item.identifier || "未知区域"}`,
              },
              data: [
                {
                  name: item.identifier || "未知区域",
                  coords: validCoords, // 确保此处是经过校验的有效二维数组
                },
              ],
            };
          })
          .filter((series) => series !== null);

        option.series.push(...pathSeries);
        chart.value.setOption(option);
      } catch (error) {
        console.error("加载路径数据失败：", error);
        areaChecked.value = false;
      }
    } else {
      const option = chart.value.getOption();
      option.series = option.series.filter((s) => {
        const seriesName = s.name || "";
        return seriesName !== pathSeriesName;
      });
      chart.value.setOption(option, true);
      pathData.value = [];
    }
  },
  { immediate: false }
);

// 监听数据变化
watch(
  () => [props.areaStatic1],
  async () => {
    console.log(props.areaStatic1, "区域预测选项");
    // 直接调用优化后的 forceUpdateGraphic，无需等待额外延时（若有卡顿可加 20ms 延时）
    forceUpdateGraphic();
    // 后续的 updateAirports 逻辑正常执行，互不影响
    await new Promise((resolve) => setTimeout(resolve, 20));
    updateAirports();
  },
  { deep: true }
);

// 组件生命周期
onMounted(() => {
  const initTimer = setTimeout(() => {
    clearTimeout(initTimer);
    nextTick(async () => {
      if (!chartRef.value) return;
      chart.value = echarts.init(chartRef.value, null, {
        renderer: "canvas",
        useDirtyRect: true,
      });
      const dataLoaded = await loadMapData();
      if (!dataLoaded) {
        return;
      }
      isReady.value = true;
      initChart();
    });
  }, 100);
});

// 窗口大小监听
watch(
  () => chartRef.value?.clientWidth,
  (newWidth) => {
    if (newWidth && isReady.value) {
      chart.value.resize({ animation: { duration: 300 } });
    }
  }
);

// 组件销毁
onUnmounted(() => {
  if (chart.value) {
    chart.value.off("dblclick");
    // 销毁前移除路径系列
    const option = chart.value.getOption();
    const pathSeriesIndexes = option.series
      .map((series, index) => (series.name === pathSeriesName ? index : -1))
      .filter((index) => index !== -1);
    pathSeriesIndexes.forEach((index) => option.series.splice(index, 1));
    chart.value.setOption(option);

    chart.value.dispose();
    chart.value = null;
  }
  isReady.value = false;
  pathData.value = []; // 清空路径数据
});
</script>

<style scoped>
.mapCheckedBox {
  position: absolute;
  left: 20px;
  z-index: 1;
  top: 17px;
  .white-text-checkbox :deep(.el-checkbox__label) {
    color: #ffffff !important;
    font-size: 14px;
  }
}
.mapTabs {
  position: absolute;
  left: 350px;
  bottom: -54px;
  .tab {
    cursor: pointer;
    float: left;
    margin-right: 8px;
    color: #c5d6e6;
    font-size: 14px;
    text-align: center;
    width: 100px;
    height: 44px;
    line-height: 44px;
    background-image: url("../../../assets/images/raim/tabUnChange.png");
    background-repeat: no-repeat;
    background-size: contain;
    background-position: center;
  }
  .tabs {
    padding: 0 15px;
    line-height: 22px;
  }
  .tabs1 {
    padding: 0 20px;
    line-height: 22px;
  }
  .tabCur {
    color: #fff;
    background-image: url("../../../assets/images/raim/tabChange.png");
  }
}

.map-container {
  position: relative;
  width: 900px;
  float: left;
  height: 675px;
  margin-top: 30px;
  margin-left: 30px;
}
.chart-container {
  width: 900px;
  height: 675px;
  background: transparent;
}
</style>
